﻿using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System;
using System.Text;
using System.Windows;

namespace Client
{
    public partial class MainWindow : Window
    {
        private IMqttClient _mqttClient;
        private IMqttClientOptions _mqttOptions;

        public MainWindow()
        {
            InitializeComponent();

            // 初始化 MQTT 客户端
            var factory = new MqttFactory();
            _mqttClient = factory.CreateMqttClient();
            txtServerIP.Text = "127.0.0.1";
            txtServerPort.Text = "1155";
            txtUsername.Text = "123";
            txtPassword.Password = "123";
            txtClientName.Text=Guid.NewGuid().ToString().ToUpper().Replace("-","").Substring(0,6);
        }

        // 连接按钮点击事件
        private async void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取用户输入的服务器信息
                string serverIP = txtServerIP.Text;
                int serverPort = int.Parse(txtServerPort.Text);
                string username = txtUsername.Text;
                string password = txtPassword.Password;

                // 设置连接选项
                _mqttOptions = new MqttClientOptionsBuilder()
                    .WithTcpServer(serverIP, serverPort) // 连接服务器
                    .WithCredentials(username, password) // 设置用户名和密码
                    .WithClientId(txtClientName.Text)
                    .Build();

                // 连接 MQTT 服务器
                await _mqttClient.ConnectAsync(_mqttOptions, CancellationToken.None);
                btnDisconnect.IsEnabled = true;
                btnConnect.IsEnabled = false;
                AppendLog("连接成功！");

                // 设置接收到消息时的回调
                _mqttClient.UseApplicationMessageReceivedHandler(e =>
                {
                    string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                    AppendLog($"接收到消息: {message}");
                });
            }
            catch (Exception ex)
            {
                AppendLog($"连接失败: {ex.Message}");
            }
        }

        // 断开连接按钮点击事件
        private async void btnDisconnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await _mqttClient.DisconnectAsync();
                btnConnect.IsEnabled = true;
                btnDisconnect.IsEnabled = false;
                AppendLog("已断开连接");
            }
            catch (Exception ex)
            {
                AppendLog($"断开连接失败: {ex.Message}");
            }
        }

        // 发布按钮点击事件
        private async void btnPublish_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string topic = txtPublishTopic.Text;
                string message = txtMessage.Text;

                var mqttMessage = new MqttApplicationMessageBuilder()
                    .WithTopic(topic)
                    .WithPayload(message)
                    .WithAtLeastOnceQoS()
                    .Build();

                // 发布消息
                await _mqttClient.PublishAsync(mqttMessage, CancellationToken.None);
                AppendLog($"已发布消息到主题 '{topic}': {message}");
            }
            catch (Exception ex)
            {
                AppendLog($"发布消息失败: {ex.Message}");
            }
        }

        // 添加订阅按钮点击事件
        private async void btnSubscribe_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string topic = txtSubscribeTopic.Text;
                if (!string.IsNullOrEmpty(topic))
                {
                    // 订阅主题
                    await _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).Build());
                    AppendLog($"已订阅主题: {topic}");
                    txtSubscribeList.AppendText(topic + Environment.NewLine);
                }
                else
                {
                    AppendLog("请输入有效的订阅主题");
                }
            }
            catch (Exception ex)
            {
                AppendLog($"订阅失败: {ex.Message}");
            }
        }

        // 日志输出方法
        private void AppendLog(string message)
        {
            Dispatcher.Invoke(() => {
                txtClientLog.AppendText($"{DateTime.Now:HH:mm:ss} - {message}{Environment.NewLine}");
                txtClientLog.ScrollToEnd();
            });
            
        }

        // 窗口关闭时断开连接
        private async void Window_Closed(object sender, EventArgs e)
        {
            if (_mqttClient.IsConnected)
            {
                await _mqttClient.DisconnectAsync();
            }
        }
    }
}
